<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>DllCall</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="../static/theme.css" rel="stylesheet" type="text/css" />
<script src="../static/content.js" type="text/javascript"></script>
</head>
<body>

<h1>DllCall()</h1>

<p>Calls a function inside a DLL, such as a standard Windows API function.</p>

<pre class="Syntax">Result := DllCall(&quot;[DllFile\]Function&quot; [, Type1, Arg1, Type2, Arg2, &quot;Cdecl ReturnType&quot;])</pre>
<h3>Parameters</h3>
<dl>

  <dt>Result</dt>
  <dd><p>DllCall returns the actual value returned by the function. If the function is of a type that does not return a value, the result is an undefined integer. If the function cannot be called due to an <a href="#error">error</a>, the return value is blank (an empty string).</p></dd>

  <dt>[DllFile\]Function</dt>
  <dd><p>The DLL or EXE file name followed by a backslash and the name of the function. For example: <code>&quot;MyDLL\MyFunction&quot;</code> (the file extension &quot;.dll&quot; is the default when omitted). If an absolute path isn't specified, <em>DllFile</em> is assumed to be in the system's PATH or <a href="../Variables.htm#WorkingDir">A_WorkingDir</a>.</p>
      <p><em><a name="std"></a>DllFile</em> may be omitted when calling a function that resides in User32.dll, Kernel32.dll, ComCtl32.dll, or Gdi32.dll. For example, <code>&quot;User32\IsWindowVisible&quot;</code> produces the same result as <code>&quot;IsWindowVisible&quot;</code>.</p>
      <p>If no function can be found by the given name, an A (ANSI) or W (Unicode) suffix is automatically appended based on which version of AutoHotkey is running the script. For example, <code>&quot;MessageBox&quot;</code> is the same as <code>&quot;MessageBoxA&quot;</code> in ANSI versions and <code>&quot;MessageBoxW&quot;</code> in Unicode versions.</p>
      <p>Performance can be dramatically improved when making <em>repeated</em> calls to a DLL by <a href="#load">loading it beforehand</a>.</p>
    <p>In v1.0.46.08+, this parameter may also consist solely of an integer, which is interpreted as the address of the function to call. Sources of such addresses include <a href="#COM">COM</a> and <a href="RegisterCallback.htm">RegisterCallback()</a>.</p></dd>

  <dt>Type1, Arg1</dt>
  <dd><p>Each of these pairs represents a single parameter to be passed to the function. The number of pairs is unlimited. For <em>Type</em>, see the <a href="#types">types table</a> below. For <em>Arg</em>, specify the value to be passed to the function.</p></dd>

  <dt>Cdecl ReturnType</dt>
  <dd><p><a name="cdecl"></a>The word <em>Cdecl</em> is normally omitted because most functions use the standard calling convention rather than the &quot;C&quot; calling convention (functions such as wsprintf that accept a varying number of arguments are one exception to this). If you omit Cdecl but the call yields <a href="#An">ErrorLevel A<strong>n</strong></a> -- where <strong>n</strong> is the total size of the arguments you passed -- <em>Cdecl</em> might be required. Note that most object-oriented C++ functions use the <i>thiscall</i> convention, which is not supported.</p>
      <p>If present, the word <em>Cdecl</em> should be listed before the return type (if any). Separate each word from the next with a space or tab. For example: <code>&quot;Cdecl Str&quot;</code>.</p>
      <p><span class="ver">[AHK_L 53+]:</span> Since a separate "C" calling convention does not exist in 64-bit code, <i>Cdecl</i> may be specified but has no effect on 64-bit builds of AutoHotkey.</p>
      <p><em>ReturnType</em>: If the function returns a 32-bit signed integer (Int), BOOL, or nothing at all, <em>ReturnType</em> may be omitted. Otherwise, specify one of the argument types from the <a href="#types">types table</a> below. The <a href="#asterisk">asterisk suffix</a> is also supported.</p></dd>

</dl>

<h3 id="types">Types of Arguments and Return Values</h3>
<table class="info">
<tr>
<td>Str</td>
<td><p><a name="str"></a>A string such as &quot;Blue&quot; or MyVar. If the called function modifies the string and the argument is a naked variable, its contents will be updated. For example, the following call would convert the contents of <em>MyVar</em> to uppercase: <code>DllCall(&quot;CharUpper&quot;, &quot;Str&quot;, <i>MyVar</i>)</code>.</p>
  <p>However, if the function is designed to store a string larger than a variable's current capacity, ensure that the variable is large enough before calling the function. This can be achieved by calling <code><a href="VarSetCapacity.htm">VarSetCapacity(MyVar, 123)</a></code>, where 123 is the length that <em>MyVar</em> must be able to hold.</p>
  <p>A <em>Str</em> argument must not be an <a href="../Variables.htm#Expressions">expression</a> that evaluates to a number (such as i+1). If it is, the function is not called and ErrorLevel is set to -2.</p>
  <p>The <a href="#asterisk">asterisk variable</a> &quot;Str*&quot; is supported but rarely used. It can be used with functions that expect something like &quot;TCHAR **&quot; or &quot;LPTSTR *&quot;.</p>
  <p>Note: When passing a string to a function, be aware what <a href="../Compat.htm#DllCall"><i>type</i> of string</a> the function expects.</p></td>
</tr>
<tr>
  <td><a name="astr"></a><a name="wstr"></a>AStr<br>WStr</td>
  <td><span class="ver">[AHK_L 42+]:</span> An <b>A</b>NSI or Unicode (<b>W</b>ide character) string. See <a href="../Compat.htm#DllCall">Script Compatibility</a> for equivalent Win32 types and other details.</td>
</tr>
<tr>
  <td>Int64</td>
  <td>A 64-bit integer, whose range is -9223372036854775808 (-0x8000000000000000) to 9223372036854775807 (0x7FFFFFFFFFFFFFFF).</td>
</tr>
<tr>
  <td>Int</td>
  <td id="Int"><p>A 32-bit integer (the most common integer type), whose range is -2147483648 (-0x80000000) to 2147483647 (0x7FFFFFFF). An Int is sometimes called a &quot;Long&quot;.</p>
    <p>An Int should also be used for each BOOL argument expected by a function (a BOOL value should be either 1 or 0).</p>
    <p>An <a href="#unsigned">unsigned</a> Int (UInt) is also used quite frequently, such as for DWORD.</p></td>
</tr>
<tr>
  <td>Short</td>
  <td>A 16-bit integer, whose range is -32768 (-0x8000) to 32767 (0x7FFF). An <a href="#unsigned">unsigned</a> Short (UShort) can be used with functions that expect a WORD.</td>
</tr>
<tr>
  <td>Char</td>
  <td>An 8-bit integer, whose range is -128 (-0x80) to 127 (0x7F). An <a href="#unsigned">unsigned</a> character (UChar) can be used with functions that expect a BYTE.</td>
</tr>
<tr>
  <td>Float</td>
  <td>A 32-bit floating point number, which provides 6 digits of precision.</td>
</tr>
<tr>
  <td>Double</td>
  <td>A 64-bit floating point number, which provides 15 digits of precision.</td>
</tr>
<tr>
  <td>Ptr</td>
  <td id="ptr"><p><span class="ver">[AHK_L 42+]:</span> A <a href="../Variables.htm#PtrSize">pointer-sized</a> integer, equivalent to Int or Int64 depending on whether the exe running the script is 32-bit or 64-bit. <i>Ptr</i> should be used for pointers to arrays or structures (such as RECT* or LPPOINT) and almost all handles (such as HWND, HBRUSH or HBITMAP). If the parameter is a pointer to a single numeric value such as LPDWORD or int*, generally the * or P suffix should be used instead of &quot;Ptr&quot;.</p>
  <p><i>Ptr</i> can also be used with the * or P suffix; it should be used with functions that output a pointer via LPVOID* or similar.</p>
  <p><i>UPtr</i> is also valid, but is only unsigned in 32-bit builds as AutoHotkey does not support unsigned 64-bit integers.</p>
  <p>If compatibility with older versions of AutoHotkey is required, use a variable type as shown below:</p>
  <pre>Ptr := A_PtrSize ? "Ptr" : "UInt" <em>; If A_PtrSize is not defined, use UInt instead.</em>
DllCall("DeleteFile", Ptr, &amp;filename) <em>; Omit the quote marks around Ptr.</em></pre>
  <p>Note: To pass a <strong>NULL</strong> handle or pointer, pass the integer 0.</p></td>
</tr>
<tr>
  <td>* or P<br>
    (suffix)</td>
  <td id="asterisk"><p>Append an asterisk (with optional preceding space) to any of the above types to cause the address of the argument to be passed rather than the value itself (the called function must be designed to accept it). Since the value of such an argument might be modified by the function, whenever a naked variable is passed as the argument, that variable's contents will be updated. For example, the following call would pass the contents of MyVar to MyFunction by address, but would also update MyVar to reflect any changes made to it by MyFunction: <code>DllCall(&quot;MyDll\MyFunction&quot;, &quot;Int*&quot;, MyVar)</code>.</p>
    <p>In general, an asterisk is used whenever a function has an argument type or return type that starts with &quot;LP&quot;. The most common example is LPDWORD, which is a pointer to a DWORD. Since a DWORD is an unsigned 32-bit integer, use &quot;UInt*&quot; or &quot;UintP&quot; to represent LPDWORD. An asterisk should not be used for string types such as LPTSTR, pointers to structures such as LPRECT, or arrays; for these, <a href="#str">&quot;Str&quot;</a> or &quot;Ptr&quot; should be used, depending on whether you pass a variable or its address.</p>
    <p>Note: &quot;Char*&quot; is not the same as <a href="#str">&quot;Str&quot;</a> because &quot;Char*&quot; passes the address of an 8-bit number, whereas <a href="#str">&quot;Str&quot;</a> passes the address of a series of characters which may be either 8-bit (ANSI) or 16-bit (Unicode), depending on the version of AutoHotkey. Similarly, &quot;UInt*&quot; passes the address of a 32-bit number, so should not be used if the function expects an array of values or a structure larger than 32 bits.</p>
    <p>Since variables in AutoHotkey have no fixed type, the address passed to the function points to temporary memory rather than the variable itself. It is not necessary to call <a href="VarSetCapacity.htm">VarSetCapacity</a> on the variable as DllCall will update it correctly after the function returns.</p>
    </td>
</tr>
<tr>
  <td>U (prefix)</td>
  <td><p><a name="unsigned"></a>Prepend the letter U to any of the integer types above to interpret it as an unsigned integer (UInt64, UInt, UShort, and UChar). Strictly speaking, this is necessary only for return values and <a href="#asterisk">asterisk variables</a> because it does not matter whether an argument passed by value is unsigned or signed (except for Int64).</p>
    <p>If a negative integer is specified for an unsigned argument, the integer wraps around into the unsigned domain. For example, when -1 is sent as a UInt, it would become 0xFFFFFFFF.</p>
    <p><em>Unsigned</em> 64-bit integers produced by a function are not supported. Therefore, to work with numbers greater or equal to 0x8000000000000000, omit the U prefix and interpret any negative values received from the function as large integers. For example, a function that yields -1 as an Int64 is really yielding 0xFFFFFFFFFFFFFFFF if it is designed to yield a UInt64.</p></td>
</tr>
</TABLE>
<p><strong>Note</strong>: When specifying an argument type or return type that does not contain a space or asterisk, the quotes around it may be omitted. For example, <code>Str</code> can be used in place of <code>&quot;Str&quot;</code> and <code>CDecl</code> in place of <code>&quot;CDecl&quot;</code>. In addition, the letter P may be used in place of asterisk to allow the quotes to be omitted there as well. For example: <code>UIntP</code>.</p>

<h3 id="error">ErrorLevel</h3>
<p><span class="ver">[v1.1.04+]</span> This function is able to throw an exception on failure. For more information, see <a href="Catch.htm#RuntimeErrors">Runtime Errors</a>.</p>
<p><a href="../misc/ErrorLevel.htm">ErrorLevel</a> is set to one of the following values to indicate whether the call succeeded or failed.</p>
<p><strong>0</strong>: Success.</p>
<p><strong>-1</strong> (negative 1): The <em>[DllFile\]Function</em> parameter is a floating point number. A string or positive integer is required.</p>
<p><strong>-2</strong>: The <a href="#types">return type</a> or one of the specified <a href="#types">arg types</a> is invalid. This error can also be caused by passing an <a href="../Variables.htm#Expressions">expression</a> that evaluates to a number to a string (<a href="#str">str</a>) argument.</p>
<p><strong>-3</strong>: The specified <em>DllFile</em> could not be accessed or loaded. If no explicit path was specified for <em>DllFile</em>, the file must exist in the system's PATH or <a href="../Variables.htm#WorkingDir">A_WorkingDir</a>. This error might also occur if the user lacks permission to access the file, or if AutoHotkey is 32-bit and the DLL is 64-bit or vice versa.</p>
<p><strong>-4</strong>: The specified function could not be found inside the DLL.</p>
<p><strong>N</strong> (any positive number): The function was called but it aborted with fatal exception number <strong>N</strong> (for example, 0xC0000005 means &quot;access violation&quot;). In such cases, the function returns a blank value (empty string), but any <a href="#asterisk">asterisk variables</a> are still updated. An example of a fatal exception is dereferencing an invalid pointer such as NULL. Since a <a href="#cdecl">Cdecl</a> function never produces the <em>&quot;An&quot;</em> error in the next paragraph, it may generate an exception when too few arguments are passed to it.</p>
<p><strong><a name="An"></a>An</strong> (the letter A followed by an integer <strong>n</strong>): The function was called but was passed too many or too few arguments. &quot;<strong>n</strong>&quot; is the number of bytes by which the argument list was incorrect. If <strong>n</strong> is positive, too many arguments (or arguments that were too large) were passed, or the call requires <a href="#cdecl">CDecl</a>. If <strong>n</strong> is negative, too few arguments were passed. This situation should be corrected to ensure reliable operation of the function. The presence of this error may also indicate that an exception occurred, in which case the function returns a blank value. Note that due to the x64 calling convention, 64-bit builds never set ErrorLevel to <b>An</b>.</p>

<h3 id="except">Exceptions and A_LastError</h3>
<p>In spite of the built-in exception handling, it is still possible to crash a script with DllCall. This can happen when a function does not directly generate an exception but yields something inappropriate, such as a bad pointer or a string that is not terminated. This might not be the function's fault if the script passed it an unsuitable value such as a bad pointer or a <a href="#str">&quot;str&quot;</a> with insufficient capacity. A script can also crash when it specifies an inappropriate argument type or return type, such as claiming that an ordinary integer yielded by a function is an <a href="#asterisk">asterisk variable</a> or <a href="#str">str</a>.</p>
<p><a name="LastError"></a>The built-in variable <strong>A_LastError</strong> contains the result of the operating system's GetLastError() function, which is called immediately after the function is called (this has no measurable impact on performance). A_LastError is a number between 0 and 4294967295 (always formatted as decimal, not hexadecimal). Like <a href="../misc/ErrorLevel.htm">ErrorLevel</a>, A_LastError is a per-thread setting; that is, interruptions by other <a href="../misc/Threads.htm">threads</a> cannot change it. However, A_LastError is also set by <a href="Run.htm#LastError">Run/RunWait</a>.</p>

<h3 id="load">Performance</h3>
<p>When making repeated calls to a DLL, performance can be dramatically improved by loading it explicitly (<em>this is not necessary for a <a href="#std">standard DLL</a> such as User32 because it is always resident</em>). This practice avoids the need for DllCall to internally call LoadLibrary and FreeLibrary each time. For example:</p>
<pre>hModule := DllCall(&quot;<strong>LoadLibrary</strong>&quot;, &quot;Str&quot;, &quot;MyFunctions.dll&quot;, &quot;Ptr&quot;)  <em>; Avoids the need for DllCall() in the loop to load the library.</em>
Loop, C:\My Documents\*.*, , 1
    result := DllCall(&quot;MyFunctions\BackupFile&quot;, &quot;Str&quot;, A_LoopFileFullPath)
DllCall(&quot;<strong>FreeLibrary</strong>&quot;, &quot;Ptr&quot;, hModule)  <em>; To conserve memory, the DLL may be unloaded after using it.</em></pre>
<p>In v1.0.46.08+, even faster performance can be achieved by looking up the function's address beforehand. For example:</p>
<pre><em>; In the following example, if the DLL isn't yet loaded, use LoadLibrary in place of GetModuleHandle.</em>
<strong>MulDivProc</strong> := DllCall(&quot;GetProcAddress&quot;, Ptr, DllCall(&quot;GetModuleHandle&quot;, Str, &quot;<strong>kernel32</strong>&quot;, &quot;Ptr&quot;), AStr, &quot;<strong>MulDiv</strong>&quot;, &quot;Ptr&quot;)
Loop 500
    DllCall(<strong>MulDivProc</strong>, Int, 3, Int, 4, Int, 3)</pre>
<p><span class="ver">[AHK_L 31+]:</span> If DllCall's first parameter is a literal string such as <code>"MulDiv"</code> and the DLL containing the function is ordinarily loaded before the script starts, the string is automatically resolved to a function address. This built-in optimization is more effective than the example shown above.</p>
<p>Also, adding the line <a href="_NoEnv.htm">#NoEnv</a> anywhere in the script improves DllCall's performance when unquoted parameter types are used (e.g. Int vs. &quot;Int&quot;).</p>
<p>Finally, when passing a string-variable to a function that will not change the length of the string, performance is improved by passing the variable <a href="../Variables.htm#amp">by address</a> (e.g. &amp;MyVar) rather than as a &quot;<a href="#str">str</a>&quot; (especially when the string is very long). The following example converts a string to uppercase: <code>DllCall(&quot;CharUpper&quot;, <strong>Ptr</strong>, <strong>&amp;</strong>MyVar, Ptr)</code>.</p>

<h3 id="struct">Structures and Arrays</h3>
<p>A structure is a collection of <em>members</em> (fields) stored adjacently in memory. Most members tend to be integers.</p>
<p>Functions that accept the address of a structure (or a memory-block array) can be called by storing the structure's raw binary data in a normal variable. The following steps are generally used:</p>
<p>1) Call <code><a href="VarSetCapacity.htm">VarSetCapacity</a>(MyStruct, 123, 0)</code> to ensure that the target variable is large enough to hold the structure's data. Replace 123 with a number that is at least as large as the size of the structure. Specifying zero as the last parameter is optional; it initializes all members to be binary zero, which is typically used to avoid calling NumPut() as often in the next step.</p>
<p>2) If the target function uses the values initially in the structure, call <code><a href="NumPut.htm">NumPut</a>(123, MyStruct, 4, "UInt")</code> to initialize any members that should be non-zero. Replace 123 with the integer to be put into the target member (or specify <code>&amp;Var</code> to store the <a href="../Variables.htm#amp">address</a> of a variable). Replace 4 with the offset of the target member (see step #4 for description of &quot;offset&quot;). Replace "UInt" with the appropriate type or omit it if the member is a pointer or handle.</p>
<p>3) Call the target function, passing the <a href="../Variables.htm#amp">address</a> of MyStruct as a UInt (or Ptr in AHK_L 42+) argument. For example, <code>DllCall(&quot;MyDll\MyFunc&quot;, Ptr, <strong>&amp;</strong>MyStruct)</code>. The function will examine and/or change some of the members.</p>
<p>4) Use <code>MyInteger := <a href="NumGet.htm">NumGet</a>(MyStruct, 4, "UInt")</code> to retrieve any desired integers from the structure. Replace 4 with the offset of the target member in the structure. The first member is always at offset 0. The second member is at offset 0 plus the size of the first member (typically 4). Members beyond the second are at the offset of the previous member plus the size of the previous member. Most members -- such as DWORD, Int, and <a href="#Int">other types of 32-bit integers</a> -- are 4 bytes in size. Replace "UInt" with the appropriate type or omit it if the member is a pointer or handle.</p>
<p>See <a href="#ExStruct">Structure Examples</a> for actual usages.</p>
<h3 id="limits">Known Limitations</h3>
<p>When a <a href="../Variables.htm#amp">variable's address</a> (e.g. <code>&amp;MyVar</code>) is passed to a function and that function alters the length of the variable's contents, subsequent uses of the variable may behave incorrectly. To fix this, do one of the following: 1) Pass MyVar as a <a href="#str">&quot;Str&quot;</a> argument rather than as a Ptr/address; 2) In v1.0.44.03+, call <code><a href="VarSetCapacity.htm#neg1">VarSetCapacity(MyVar, -1)</a></code> to update the variable's internally-stored length after calling DllCall.</p>
<p>Any binary zero stored in a variable by a function hides all data to the right of the zero; that is, such data cannot be accessed or changed by most commands and functions. However, such data can be manipulated by the <a href="../Variables.htm#amp">address operator</a> and <a href="NumPut.htm">NumPut</a>/<a href="NumGet.htm">NumGet</a>, as well as DllCall itself.</p>
<p>A function that returns the address of one of the strings that was passed into it might return an identical string in a different memory address than expected. For example calling <code>CharLower(CharUpper(MyVar))</code> in a programming language would convert <em>MyVar</em>'s contents to lowercase. But when the same is done with DllCall(), <em>MyVar</em> would be uppercase after the following call because CharLower would have operated on a different/temporary string whose contents were identical to <em>MyVar</em>:</p>
<pre>MyVar = ABC
result := DllCall(&quot;CharLower&quot;, <strong><u>str</u></strong>, DllCall(&quot;CharUpper&quot;, Str, MyVar, <strong><u>Str</u></strong>), Str)</pre>
<p>To work around this, change the two underlined &quot;Str&quot; values above to Ptr. This interprets CharUpper's return value as a pure address that will get passed as an integer to CharLower.</p>
<p>Certain limitations may be encountered when dealing with strings. For details, see <a href="../Compat.htm#DllCall">Script Compatibility</a>.</p>
<h3 id="COM">Component Object Model (COM)</h3>
<p>COM objects which are accessible to VBScript and similar languages are typically also accessible to AutoHotkey via <a href="ComObjCreate.htm">ComObjCreate</a>, <a href="ComObjGet.htm">ComObjGet</a> or <a href="ComObjActive.htm">ComObjActive</a> and the built-in <a href="../Objects.htm#Usage_Objects">object syntax</a>.</p>
<p>COM objects which don't support <a href="http://msdn.microsoft.com/en-us/library/ms221608.aspx">IDispatch</a> can be used with DllCall by retrieving the address of a function from the virtual function table of the object's interface. For more details, see <a href="#ExTaskbar">the example</a> further below.</p>
<p>Much of the .NET Framework is also accessible via COM and DllCall. See <a href="http://www.autohotkey.com/forum/topic26191.html">http://www.autohotkey.com/forum/topic26191.html</a>.
</p>

<h3>Related</h3>
<p><a href="../Compat.htm#DllCall">Script Compatibility</a>, <a href="PostMessage.htm">PostMessage</a>, <a href="OnMessage.htm">OnMessage()</a>, <a href="RegisterCallback.htm">RegisterCallback()</a>, <a href="Run.htm">Run</a>, <a href="VarSetCapacity.htm">VarSetCapacity</a>, <a href="../Functions.htm">Functions</a>, <a href="SysGet.htm">SysGet</a>, <a href="http://msdn.microsoft.com/library/">MSDN Library</a></p>
<h3>Examples</h3>
<pre class="NoIndent"><em>; Example: Calls the Windows API function &quot;MessageBox&quot; and report which button the user presses.</em>

WhichButton := DllCall(&quot;MessageBox&quot;, &quot;Int&quot;, &quot;0&quot;, &quot;Str&quot;, &quot;Press Yes or No&quot;, &quot;Str&quot;, &quot;Title of box&quot;, &quot;Int&quot;, 4)
MsgBox You pressed button #%WhichButton%.</pre>

<pre class="NoIndent"><em>; Example: Changes the desktop wallpaper to the specified bitmap (.bmp) file.</em>

DllCall(&quot;SystemParametersInfo&quot;, UInt, 0x14, UInt, 0, Str, <i>A_WinDir <strong>.</strong> &quot;\winnt.bmp&quot;</i>, UInt, 2)</pre>

<pre class="NoIndent"><em>; Example: Calls the API function &quot;IsWindowVisible&quot; to find out if a Notepad window is visible.</em>

DetectHiddenWindows On
if not DllCall(&quot;IsWindowVisible&quot;, &quot;Ptr&quot;, WinExist(&quot;Untitled - Notepad&quot;))  <em>; WinExist() returns an HWND.</em>
    MsgBox The window is not visible.</pre>

<pre class="NoIndent"><em>; Example: Calls the API's wsprintf() to pad the number 432 with leading zeros to make it 10 characters wide (0000000432).</em>

VarSetCapacity(ZeroPaddedNumber, 20)  <em>; Ensure the variable is large enough to accept the new string.</em>
DllCall(&quot;wsprintf&quot;, &quot;Str&quot;, ZeroPaddedNumber, &quot;Str&quot;, &quot;%010d&quot;, &quot;Int&quot;, 432, &quot;Cdecl&quot;)  <em>; Requires the Cdecl calling convention.</em>
MsgBox %ZeroPaddedNumber%</pre>

<pre class="NoIndent"><a name="QPC"></a><em>; Example: Demonstrates QueryPerformanceCounter(), which gives more precision than <a href="../Variables.htm#TickCount">A_TickCount's</a> 10ms.</em>

DllCall(&quot;QueryPerformanceCounter&quot;, &quot;Int64*&quot;, CounterBefore)
Sleep 1000
DllCall(&quot;QueryPerformanceCounter&quot;, &quot;Int64*&quot;, CounterAfter)
MsgBox % &quot;Elapsed QPC time is &quot; . CounterAfter - CounterBefore</pre>

<pre class="NoIndent"><em>; Example: This is a hotkey that temporarily reduces the mouse cursor's speed, which facilitates precise positioning.
; Hold down the F1 key to slow down the cursor. Release it to return to original speed.</em>

F1::
SPI_GETMOUSESPEED = 0x70
SPI_SETMOUSESPEED = 0x71
<em>; Retrieve the current speed so that it can be restored later:</em>
<strong>DllCall</strong>(&quot;SystemParametersInfo&quot;, UInt, SPI_GETMOUSESPEED, UInt, 0, UIntP, OrigMouseSpeed, UInt, 0)
<em>; Now set the mouse to the slower speed specified in the next-to-last parameter (the range is 1-20, 10 is default):</em>
<strong>DllCall</strong>(&quot;SystemParametersInfo&quot;, UInt, SPI_SETMOUSESPEED, UInt, 0, Ptr, <strong>3</strong>, UInt, 0)
KeyWait F1  <em>; This prevents keyboard auto-repeat from doing the DllCall repeatedly.</em>
return

F1 up::<strong>DllCall</strong>(&quot;SystemParametersInfo&quot;, UInt, 0x71, UInt, 0, Ptr, OrigMouseSpeed, UInt, 0)  <em>; Restore the original speed.</em></pre>

<pre class="NoIndent"><a name="GetChildHWND"></a><em>; Example: When passed a window's Unique ID and the text or ClassNN of one of its controls,
; the following function returns the HWND (unique ID) of that control.
; v1.0.43.06+: This function has been superseded by the following command, which is more accurate.</em>

<a href="ControlGet.htm#Hwnd">ControlGet, OutputVar, Hwnd,, ClassNN, WinTitle</a></pre>

<pre class="NoIndent"><em>; Example: Monitors the active window and display the position of its vertical scroll bar in its
; focused control (with real-time updates). This requires v1.0.43.06+ because it uses <a href="ControlGet.htm#Hwnd">ControlGet Hwnd</a>.</em>

#Persistent
SetTimer, WatchScrollBar, 100
return

WatchScrollBar:
ActiveWindow := WinExist(&quot;A&quot;)
if not ActiveWindow  <em>; No active window.</em>
    return
ControlGetFocus, FocusedControl, ahk_id %ActiveWindow%
if not FocusedControl  <em>; No focused control.</em>
    return
<em>; Display the vertical or horizontal scroll bar's position in a ToolTip:</em>
ControlGet, ChildHWND, Hwnd,, %FocusedControl%, ahk_id %ActiveWindow%
ToolTip % <strong>DllCall</strong>(&quot;GetScrollPos&quot;, &quot;Ptr&quot;, ChildHWND, &quot;Int&quot;, 1)  <em>;  Last parameter is 1 for SB_VERT, 0 for SB_HORZ.</em>
return</pre>

<pre class="NoIndent"><a name="file"></a><em>; Example: This is a working script that writes some text to a file then reads it back into memory (requires v1.0.34+).
; This method can be used to help performance in cases where multiple files are being read or written simultaneously.
; in AHK_L 42+, <a href="FileOpen.htm#writeread">the same can be achieved</a> using <a href="FileOpen.htm">FileOpen</a>.</em>

FileSelectFile, FileName, S16,, Create a new file:
if FileName =
    return
GENERIC_WRITE = 0x40000000  <em>; Open the file for writing rather than reading.</em>
CREATE_ALWAYS = 2  <em>; Create new file (overwriting any existing file).</em>
hFile := <strong>DllCall</strong>(&quot;CreateFile&quot;, Str, FileName, UInt, GENERIC_WRITE, UInt, 0, Ptr, 0, UInt, CREATE_ALWAYS, UInt, 0, Ptr, 0, Ptr)
if not hFile
{
    MsgBox Can't open &quot;%FileName%&quot; for writing.
    return
}
TestString = This is a test string.`r`n  <em>; When writing a file this way, use `r`n rather than `n to start a new line.</em>
<strong>DllCall</strong>(&quot;WriteFile&quot;, Ptr, hFile, Str, TestString, UInt, StrLen(TestString), UIntP, BytesActuallyWritten, Ptr, 0)
<strong>DllCall</strong>(&quot;CloseHandle&quot;, Ptr, hFile)  <em>; Close the file.</em>

<em>; Now that the file was written, read its contents back into memory.</em>
GENERIC_READ = 0x80000000  <em>; Open the file for reading rather than writing.</em>
OPEN_EXISTING = 3  <em>; This mode indicates that the file to be opened must already exist.</em>
FILE_SHARE_READ = 0x1 <em>; This and the next are whether other processes can open the file while we have it open.</em>
FILE_SHARE_WRITE = 0x2
hFile := <strong>DllCall</strong>(&quot;CreateFile&quot;, Str, FileName, UInt, GENERIC_READ, UInt, FILE_SHARE_READ|FILE_SHARE_WRITE, Ptr, 0, UInt, OPEN_EXISTING, UInt, 0, Ptr, 0)
if not hFile
{
    MsgBox Can't open &quot;%FileName%&quot; for reading.
    return
}
<em>; Make the variable empty for testing purposes, but ensure it retains sufficient capacity:</em>
BytesToRead := VarSetCapacity(TestString, StrLen(TestString))
<strong>DllCall</strong>(&quot;ReadFile&quot;, Ptr, hFile, Str, TestString, UInt, BytesToRead, UIntP, BytesActuallyRead, Ptr, 0)
<strong>DllCall</strong>(&quot;CloseHandle&quot;, Ptr, hFile)  <em>; Close the file.</em>
MsgBox The following string was read from the file: %TestString%</pre>

<pre class="NoIndent"><a name="HideCursor"></a><em>; Example: Hides the mouse cursor when you press Win+C. To later show the cursor, press Win+C again.
; This script is from <a href="http://www.autohotkey.com/forum/topic6107.html">www.autohotkey.com/forum/topic6107.html</a></em>

OnExit, ShowCursor  <em>; Ensure the cursor is made visible when the script exits.</em>
return

ShowCursor:
SystemCursor(&quot;On&quot;)
ExitApp

#c::SystemCursor(&quot;Toggle&quot;)  <em>; Win+C hotkey to toggle the cursor on and off.</em>

SystemCursor(OnOff=1)   <em>; INIT = &quot;I&quot;,&quot;Init&quot;; OFF = 0,&quot;Off&quot;; TOGGLE = -1,&quot;T&quot;,&quot;Toggle&quot;; ON = others</em>
{
    static AndMask, XorMask, $, h_cursor
        ,c0,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13 <em>; system cursors</em>
        , b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13   <em>; blank cursors</em>
        , h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11,h12,h13   <em>; handles of default cursors</em>
    if (OnOff = &quot;Init&quot; or OnOff = &quot;I&quot; or $ = &quot;&quot;)       <em>; init when requested or at first call</em>
    {
        $ = h                                          <em>; active default cursors</em>
        VarSetCapacity( h_cursor,4444, 1 )
        VarSetCapacity( AndMask, 32*4, 0xFF )
        VarSetCapacity( XorMask, 32*4, 0 )
        system_cursors = 32512,32513,32514,32515,32516,32642,32643,32644,32645,32646,32648,32649,32650
        StringSplit c, system_cursors, `,
        Loop %c0%
        {
            h_cursor   := DllCall( &quot;LoadCursor&quot;, &quot;Ptr&quot;,0, &quot;Ptr&quot;,c%A_Index% )
            h%A_Index% := DllCall( &quot;CopyImage&quot;, &quot;Ptr&quot;,h_cursor, &quot;UInt&quot;,2, &quot;Int&quot;,0, &quot;Int&quot;,0, &quot;UInt&quot;,0 )
            b%A_Index% := DllCall( &quot;CreateCursor&quot;, &quot;Ptr&quot;,0, &quot;Int&quot;,0, &quot;Int&quot;,0
                , &quot;Int&quot;,32, &quot;Int&quot;,32, &quot;Ptr&quot;,&amp;AndMask, &quot;Ptr&quot;,&amp;XorMask )
        }
    }
    if (OnOff = 0 or OnOff = &quot;Off&quot; or $ = &quot;h&quot; and (OnOff &lt; 0 or OnOff = &quot;Toggle&quot; or OnOff = &quot;T&quot;))
        $ = b  <em>; use blank cursors</em>
    else
        $ = h  <em>; use the saved cursors</em>

    Loop %c0%
    {
        h_cursor := DllCall( &quot;CopyImage&quot;, &quot;Ptr&quot;,%$%%A_Index%, &quot;UInt&quot;,2, &quot;Int&quot;,0, &quot;Int&quot;,0, &quot;UInt&quot;,0 )
        DllCall( &quot;SetSystemCursor&quot;, &quot;Ptr&quot;,h_cursor, &quot;UInt&quot;,c%A_Index% )
    }
}</pre>

<pre class="NoIndent" id="ExStruct"><em>; Structure Example: Pass the address of a RECT structure to GetWindowRect(), which sets the structure's
; members to the positions of the left, top, right, and bottom sides of a window (relative to the screen).</em>

Run Notepad
WinWait Untitled - Notepad  <em>; This also sets the &quot;<a href="../misc/WinTitle.htm#LastFoundWindow">last found window</a>&quot; for use with WinExist() below.</em>
VarSetCapacity(Rect, 16)  <em>; A RECT is a struct consisting of four 32-bit integers (i.e. 4*4=16).</em>
<strong>DllCall</strong>(&quot;GetWindowRect&quot;, Ptr, WinExist(), Ptr, &amp;Rect)  <em>; WinExist() returns an HWND.</em>
MsgBox % &quot;Left &quot; . <a href="NumGet.htm">NumGet</a>(Rect, 0, "Int") . &quot; Top &quot; . NumGet(Rect, 4, "Int")
    . &quot; Right &quot; . NumGet(Rect, 8, "Int") . &quot; Bottom &quot; . NumGet(Rect, 12, "Int")</pre>

<pre class="NoIndent"><em>; Structure Example: Pass to FillRect() the address of a RECT structure that indicates a part of the
; screen to temporarily paint red.</em>

VarSetCapacity(Rect, 16, 0)  <em>; Set capacity to hold four 4-byte integers and initialize them all to zero.</em>
<a href="NumPut.htm">NumPut</a>(A_ScreenWidth//2, Rect, 8, "Int")  <em>; The third integer in the structure is &quot;rect.right&quot;.</em>
NumPut(A_ScreenHeight//2, Rect, 12, "Int") <em>; The fourth integer in the structure is &quot;rect.bottom&quot;.</em>
hDC := <strong>DllCall</strong>(&quot;GetDC&quot;, "Ptr", 0, "Ptr")  <em>; Pass zero to get the desktop's device context.</em>
hBrush := <strong>DllCall</strong>(&quot;CreateSolidBrush&quot;, "UInt", 0x0000FF, "Ptr")  <em>; Create a red brush (0x0000FF is in BGR format).</em>
<strong>DllCall</strong>(&quot;FillRect&quot;, "Ptr", hDC, "Ptr", &amp;Rect, "Ptr", hBrush)  <em>; Fill the specified rectangle using the brush above.</em>
<strong>DllCall</strong>(&quot;ReleaseDC&quot;, "Ptr", 0, "Ptr", hDC)  <em>; Clean-up.</em>
<strong>DllCall</strong>(&quot;DeleteObject&quot;, "Ptr", hBrush)  <em>; Clean-up.</em></pre>

<pre class="NoIndent"><em>; Structure Example: Change the system's clock to the specified date and time. Use caution when
; changing to a date in the future as it may cause scheduled tasks to run prematurely!</em>

SetSystemTime(&quot;20051008142211&quot;)  <em>; Pass it a <a href="FileSetTime.htm#YYYYMMDD">timestamp</a> (local, not UTC).</em>

SetSystemTime(YYYYMMDDHHMISS)
<em>; Sets the system clock to the specified date and time.
; Caller must ensure that the incoming parameter is a valid date-time stamp
; (local time, not UTC). Returns non-zero upon success and zero otherwise.</em>
{
    <em>; Convert the parameter from local time to UTC for use with SetSystemTime().</em>
    UTC_Delta -= A_NowUTC, Seconds  <em>; Seconds is more accurate due to rounding issue.</em>
    UTC_Delta := Round(-UTC_Delta/60)  <em>; Round to nearest minute to ensure accuracy.</em>
    YYYYMMDDHHMISS += UTC_Delta, Minutes  <em>; Apply offset to convert to UTC.</em>

    VarSetCapacity(SystemTime, 16, 0)  <em>; This struct consists of 8 UShorts (i.e. 8*2=16).</em>

    StringLeft, Int, YYYYMMDDHHMISS, 4    <em>; YYYY (year)</em>
    <a href="NumPut.htm">NumPut</a>(Int, SystemTime, 0, &quot;UShort&quot;)
    StringMid, Int, YYYYMMDDHHMISS, 5, 2  <em>; MM (month of year, 1-12)</em>
    NumPut(Int, SystemTime, 2, &quot;UShort&quot;)
    StringMid, Int, YYYYMMDDHHMISS, 7, 2  <em>; DD (day of month)</em>
    NumPut(Int, SystemTime, 6, &quot;UShort&quot;)
    StringMid, Int, YYYYMMDDHHMISS, 9, 2  <em>; HH (hour in 24-hour time)</em>
    NumPut(Int, SystemTime, 8, &quot;UShort&quot;)
    StringMid, Int, YYYYMMDDHHMISS, 11, 2 <em>; MI (minute)</em>
    NumPut(Int, SystemTime, 10, &quot;UShort&quot;)
    StringMid, Int, YYYYMMDDHHMISS, 13, 2 <em>; SS (second)</em>
    NumPut(Int, SystemTime, 12, &quot;UShort&quot;)

    return <strong>DllCall</strong>(&quot;SetSystemTime&quot;, Ptr, &amp;SystemTime)
}</pre>

<pre class="NoIndent"><em>/* <strong>More Structure Examples:</strong>

1) See the <a href="../scripts/WinLIRC.htm">WinLIRC client script</a> for a demonstration of how to use DllCall() to make a network connection
to a TCP/IP server and receive data from it.

2) The operating system offers standard dialog boxes that prompt the user to pick a font and/or color, or an icon.
These dialogs use structures and are demonstrated at <a href="http://www.autohotkey.com/forum/topic17230.html">www.autohotkey.com/forum/topic17230.html</a>.

*/</em></pre>

<pre id="ExTaskbar" class="NoIndent"><em>/*
  Example: Temporarily remove the active window from the taskbar by using COM.

  Methods in <a href="http://msdn.microsoft.com/en-us/library/bb774652.aspx">ITaskbarList</a>'s VTable:
    IUnknown:
      0 QueryInterface  -- use <a href="ComObjQuery.htm">ComObjQuery</a> instead
      1 AddRef          -- use <a href="ObjAddRef.htm">ObjAddRef</a> instead
      2 Release         -- use <a href="ObjAddRef.htm">ObjRelease</a> instead
    ITaskbarList:
      3 HrInit
      4 AddTab
      5 DeleteTab
      6 ActivateTab
      7 SetActiveAlt
*/</em>
IID_ITaskbarList  := "{56FDF342-FD6D-11d0-958A-006097C9A090}"
CLSID_TaskbarList := "{56FDF344-FD6D-11d0-958A-006097C9A090}"

<em>; Create the TaskbarList object and store its address in tbl.</em>
tbl := <a href="ComObjCreate.htm">ComObjCreate</a>(CLSID_TaskbarList, IID_ITaskbarList)

activeHwnd := WinExist("A")

DllCall(vtable(tbl,3), "ptr", tbl)                     <em>; tbl.<a href="http://msdn.microsoft.com/en-us/library/bb774650.aspx">HrInit</a>()</em>
DllCall(vtable(tbl,5), "ptr", tbl, "ptr", activeHwnd)  <em>; tbl.<a href="http://msdn.microsoft.com/en-us/library/bb774648.aspx">DeleteTab</a>(activeHwnd)</em>
Sleep 3000
DllCall(vtable(tbl,4), "ptr", tbl, "ptr", activeHwnd)  <em>; tbl.<a href="http://msdn.microsoft.com/en-us/library/bb774646.aspx">AddTab</a>(activeHwnd)</em>

<em>; Non-dispatch objects must always be manually freed.</em>
ObjRelease(tbl)

vtable(ptr, n) {
    <em>; NumGet(ptr+0) returns the address of the object's virtual function
    ; table (vtable for short). The remainder of the expression retrieves
    ; the address of the nth function's address from the vtable.</em>
    return NumGet(NumGet(ptr+0), n*A_PtrSize)
}
</pre>

</body>
</html>
